﻿//去掉空格
function Trim(s) {
    //return s.replace(/^\s+|\s+$/g,'');
    //处理全角空格
    return s.replace(/^[\s　]+|[\s　]+$/g, '');
}



//获取字符串的长度//^^新增
function GetLen(s) {
    var len = 0;
    for (var i = 0; i < s.length; i++) {

        chrCode = s.charCodeAt(i);

        if (parseInt(chrCode) > 255) {
            len = len + 2;
        } else {
            len = len + 1;
        }
    }

    return len;
}


// 功能：取 url 后参数值。暂时处理，需要完善
// 返回：参数值。如果没有参数不存在，返回 undefined
function getQueryString(sURL, sParamName) {
    if (Trim(sURL) == "")
        return undefined;

    var arrParam;
    var sParamValue;

    arrParam = sURL.substring(sURL.indexOf("?") + 1).split("&");
    for (var i = 0; i < arrParam.length; i++) {
        if (arrParam[i].indexOf(sParamName + "=") != -1) {
            var reg = new RegExp(sParamName + "=", "g");
            return arrParam[i].replace(reg, "");
        }
    }

    return undefined;
}

// 功能：将字符编码由 Unicode 转换成 UTF8
function UnicodeToUTF8(s) {
    if (!s) {
        return "";
    }

    s = escape(s);

    s = s.replace(/%20/g, " ");
    s = s.replace(/%u(\w{4})/g, "&#x$1;");
    s = s.replace(/%(\w{2})/g, "&#x$1;");

    return s;
}

// 功能：将字符编码由 UTF8 转换成 Unicode
function UTF8ToUnicode(s) {
    // Check input param
    if (!s) {
        return "";
    }

    // Do the appropriate replacements
    s = s.replace(/&#x(\w{2});/g, function($0, $1) {
        return (unescape("%" + $1));
    });
    s = s.replace(/&#x(\w{4});/g, function($0, $1) {
        return (unescape("%u" + $1));
    });

    return s;
}

// 功能：将字符串进行 HTML 编码，以便实现从 Web 服务器到客户端的可靠的 HTTP 传输
function HtmlEncode(s) {
    s = s.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    return s.replace(/\"/g, "&quot;");
}

// 功能：将字符串进行 HTML 编码，以便实现从 Web 服务器到客户端的可靠的 HTTP 传输
function HtmlDecode(s) {
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/&amp;/g, "&");
    return s;
}


// 功能：将 HTML 编码的字符串解码
function decodeXml(s) {
    // remove all unicode encoded symbols
    try {
        s = eval('"' + s.replace(/&#x(\w\w\w\w);/g, "\\u$1").replace(/"/g, '\\"') + '"');
    }
    catch (e) { ; }
    // remove special encoding sequences
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&apos;/g, "'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/&amp;/g, "&");
    return s;
}

// 功能：对 URL 字符串进行编码，以便实现从 Web 服务器到客户端的可靠的 HTTP 传输
function URLEncode(s) {
    /*
    s = s.replace(" ", "%20");
    s = s.replace("\"", "%22");
    s = s.replace("#", "%23");
    s = s.replace("&", "%26");
    return s.replace("+", "%2B");
    */
    //解决上面代码只替换第一个特殊字符的问题
    s = s.replace(/ /g, "%20");
    s = s.replace(/"/g, "%22");
    s = s.replace(/#/g, "%23");
    s = s.replace(/&/g, "%26");
    return s.replace(/\+/g, "%2B");
}

function ConvertUserTypeToLike(searchValue) {
    var s = "";
    var sChar = "";
    var iLength = searchValue.length;

    for (var i = 0; i < iLength; i++) {
        sChar = searchValue.charAt(i);
        switch (sChar) {
            case "%": s += "[%]"; break;
            case "_": s += "[_]"; break;
            case "[": s += "[[]"; break;
            case "*": s += "%"; break;
            default: s += sChar; break;
        }
    }

    return s;
}

function GetNodeValue(input, searchName, bNoDecode) {
    if (!input || !searchName) {
        return "";
    }

    var rootStart = input.indexOf('<' + searchName + '>');

    if (rootStart == -1) {
        // could be a node with attributes
        rootStart = input.indexOf('<' + searchName + ' ');

        if (rootStart == -1) {
            return "";
        }
    }

    var startIndex = input.indexOf(">", rootStart) + 1;
    var endIndex = input.indexOf("</" + searchName + '>', startIndex);

    return bNoDecode ? input.substring(startIndex, endIndex) :
						decodeXml(input.substring(startIndex, endIndex));
}

//生成GUID
function NewGUID() {
    try {
        var TypeLib = new ActiveXObject("Scriptlet.TypeLib");
        return TypeLib.Guid;
    }
    catch (e) { }
}

// 将字符串转换为日期对象
function StringToDate(str) {
    var strDate = str.split(" ");
    var strDatepart = strDate[0].split("-");
    var dtDate = new Date(strDatepart[0], strDatepart[1] - 1, strDatepart[2]);
    return dtDate;
}

// 将日期对象转换为字符串
function DateToString(dt) {
    var decYear = dt.getFullYear();
    var decMonth = dt.getMonth() + 1;
    var decDay = dt.getDate();

    if (decMonth < 10) { sMonth = "0" + decMonth.toString(); }
    else { sMonth = decMonth.toString(); }

    if (decDay < 10) { sDay = "0" + decDay.toString(); }
    else { sDay = decDay.toString(); }

    var strDate = decYear.toString() + "-" + sMonth + "-" + sDay;
    return strDate;
}

// 功能：设置 Cookie
// 参数：iExpireDays		-- 超时期限，以天为单位（整数）
// 返回：成功	-- true；失败	-- false
function SetCookie(sName, sValue, iExpireDays) {
    if (sName != "" && sName.indexOf(";") < 0 && iExpireDays >= 0) {
        date = new Date();
        dExpires = new Date(date.getTime() + (iExpireDays * 24 * 3600 * 1000));
        document.cookie = sName + "=" + escape(sValue) + "; expires=" + dExpires.toGMTString();
    }
    else
        return false;
}

// 功能：获取 Cookie 的值
function GetCookie(sName) {
    // cookies are separated by semicolons
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++) {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }
    // a cookie with the requested name does not exist
    return null;
}

// 功能：删除 Cookie
function DelCookie(sName) {
    document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

//功能：判断字符串是否只包含英文字母和数字
//参数：sStr － 待校验字符串
//返回：符合返回 true，否则返回 false			
function IsOnlyCharNumber(sStr) {
    var regexp = /^[a-zA-Z0-9]+$/g;
    if (sStr != "" && regexp.test(sStr) == false) return false;

    return true;
}

// 功能：将自定义条件合并到查询条件 xml 中
// 参数：sUserQueryXml	-- 用户自定义条件，必须满足格式 <filter type="and/or"><condition ... /></filter>，
//		 或 <entity ...>...</entity> 格式。如果 <entity> 则 sQueryXml 的根节点名称也应该是 <entity>。
//		 sQueryXml	-- 查询条件
// 		 sType		-- 组合类型（and/or）
// 返回：xml 字符串
// 说明：如果不含实体关联查询条件，实体之间的条件只能是 and。
function appendQueryXml(sUserQueryXml, sQueryXml, sType) {
    if (Trim(sUserQueryXml) == "")
        return sQueryXml;
    if (Trim(sQueryXml) == "")
        return sUserQueryXml;

    var xmlQueryDom = new ActiveXObject("Microsoft.XMLDOM")
    xmlQueryDom.loadXML(sQueryXml);

    var xmlUserQueryDom = new ActiveXObject("Microsoft.XMLDOM")
    xmlUserQueryDom.loadXML(sUserQueryXml);

    // 1、根节点是 <filter>
    if (xmlQueryDom.documentElement.nodeName == "filter") {
        if (xmlUserQueryDom.documentElement.nodeName == "entity") {
            if (confirm("要合并的 xml 根节点不匹配！\n是否查看 xml 参数？") == true) {
                alert("sUserQueryXml:\n" + sUserQueryXml + "\n\nsQueryXml:\n" + sQueryXml);
            }
            return;
        }
        return "<filter type=\"" + sType + "\">" + sUserQueryXml + sQueryXml + "</filter>"
    }

    // 2、根节点是 <entity>
    // 2.1、校验要拼接的 xml 的根节点是否匹配
    if (xmlUserQueryDom.documentElement.nodeName == "entity") {
        if (xmlUserQueryDom.documentElement.attributes.getNamedItem("name").value != xmlQueryDom.documentElement.attributes.getNamedItem("name").value) {
            if (confirm("要合并的 xml 根节点不匹配！\n是否查看 xml 参数？") == true) {
                alert("sUserQueryXml:\n" + sUserQueryXml + "\n\nsQueryXml:\n" + sQueryXml);
            }
            return;
        }
        if (xmlUserQueryDom.documentElement.attributes.getNamedItem("primarykey").value != xmlQueryDom.documentElement.attributes.getNamedItem("primarykey").value) {
            if (confirm("要合并的 xml 根节点不匹配！\n是否查看 xml 参数？") == true) {
                alert("sUserQueryXml:\n" + sUserQueryXml + "\n\nsQueryXml:\n" + sQueryXml);
            }
            return;
        }
    }

    // 2.2、拼接 xml
    var sEntityBgnTag, sEntityEndTag, sFilter, sLink;
    var nFilter, nsLink;

    // 2.2.1、生成根节点的起始和结束标记
    sEntityBgnTag = "<entity";
    var attrsEntity = xmlQueryDom.documentElement.attributes;
    for (var i = 0; i < attrsEntity.length; i++) {
        sEntityBgnTag += " " + attrsEntity[i].nodeName + "=\"" + attrsEntity[i].value + "\"";
    }

    sEntityBgnTag += ">";

    sEntityEndTag = "</entity>";

    // 2.2.2、拼写 filter 节点字符串
    sFilter = "";

    // 2.2.2.1、sQueryXml 的 filter 节点
    nFilter = xmlQueryDom.selectNodes("/entity/filter");
    for (var i = 0; i < nFilter.length; i++) {
        sFilter += nFilter.item(i).xml;
    }

    // 2.2.2.2、sUserQueryXml 的 filter 节点
    if (xmlUserQueryDom.documentElement.nodeName == "entity")	// 如果被插入的 xml 根节点是 entity
    {
        nFilter = xmlUserQueryDom.selectNodes("/entity/filter");
        for (var i = 0; i < nFilter.length; i++) {
            sFilter += nFilter.item(i).xml;
        }
    }
    else {
        sFilter += sUserQueryXml;
    }

    // 2.2.2.3、filter 节点外包条件
    if (sFilter != "") {
        sFilter = "<filter type=\"" + sType + "\">" + sFilter + "</filter>";
    }

    // 2.2.3、拼写 link-entity 节点字符串
    sLink = "";

    // 2.2.3.1、sQueryXml 的 link-entity 节点
    nsLink = xmlQueryDom.selectNodes("/entity/link-entity");
    for (var i = 0; i < nsLink.length; i++) {
        sLink += nsLink.item(i).xml;
    }

    // 2.2.3.2、sUserQueryXml 的 link-entity 节点
    nsLink = xmlUserQueryDom.selectNodes("/entity/link-entity");
    for (var i = 0; i < nsLink.length; i++) {
        sLink += nsLink.item(i).xml;
    }

    return sEntityBgnTag + sFilter + sLink + sEntityEndTag;

}

//从链接中获取域名
function GetDomain(sUrl) {
    var re = new RegExp("^(http://|https://|)(([\\w\\-.])+)($|:|/)", "ig");
    if (re.exec(sUrl) == null) return "";

    return RegExp.$2;
}

//设置用户当前参数
function SetCurrArg(sType, sArgGUID) {
    var sURL;
    sURL = "/_controls/UserCurrArgs.aspx?mode=set&objecttype=" + escape(sType) + "&argguid=" + escape(sArgGUID) + "&rnd=" + Math.random();

    var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
    xmlDom.async = false;

    try {
        xmlDom.load(sURL);

        if (xmlDom.selectSingleNode("/xml/success").text == "1")
            return true;
        else
            return false;
    }
    catch (e) {
        return false;
    }
}

//获取用户当前参数
function GetCurrArg(sType) {
    var sURL;
    sURL = "/_controls/UserCurrArgs.aspx?mode=get&objecttype=" + escape(sType) + "&rnd=" + Math.random();

    var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
    xmlDom.async = false;

    try {
        xmlDom.load(sURL);

        if (xmlDom.selectSingleNode("/xml/success").text == "1")
            return xmlDom.selectSingleNode("/xml/argguid").text;
        else
            return "";
    }
    catch (e) {
        return "";
    }
}

// 根据 <filter...><condition.../></filter> 格式的 XML 生成 SQL 过滤条件
function Xml2Filter(sXml, entityName, primaryKey) {
    var oHTTP = new ActiveXObject("Msxml2.XMLHTTP");
    var sUrl = "/_controls/Xml2Filter.aspx?rnd=" + Math.random();
    if (entityName) sUrl += "&entityname=" + escape(entityName);
    if (primaryKey) sUrl += "&primarykey=" + escape(primaryKey);

    oHTTP.open("POST", sUrl, false);
    oHTTP.send(sXml);

    // <xml result="true/false" errormessage="错误信息！">返回结果</xml>
    var returnXML = oHTTP.responseText;

    delete (oHTTP);

    try {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.loadXML(returnXML);

        if (xmlDom.documentElement.attributes.getNamedItem("result").text == "true")		// 如果成功
            return xmlDom.documentElement.text;
        else		// 如果失败
            return "1=2";
    }
    catch (e) {
        return "1=2";
    }
}

//定义StringBuilder类 改善字符串连接操作性能 如果ie在新版本中的js引擎对+=操作做了优化，那么就没有必要用StringBuilder类做字符串加操作
function StringBuilder() {
    this._S = [];
}
StringBuilder.prototype.append = function(s) {
    this._S.push(s);
}
StringBuilder.prototype.appendRange = function() {
    for (var i = 0, n = arguments.length; i < n; i++) {
        this._S.push(arguments[i]);
    }
}
StringBuilder.prototype.toString = function() {
    return this._S.join("");
}
// XmlHttp factory
function XmlHttp() { }
XmlHttp.create = function() {
    var arrXmlhttp = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    for (var i = 0; i < arrXmlhttp.length; i++) {
        try {
            oRequest = new ActiveXObject(arrXmlhttp[i]);
            return oRequest;
        }
        catch (ex) {
            //忽略
        }
    }
    throw new Error("你的浏览器不支持XmlHttp objects");
}
// XmlDocument factory
function XmlDocument() { }
XmlDocument.create = function() {
    var arr = ["MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "Microsoft.XmlDom"];
    for (var i = 0; i < arr.length; i++) {
        try {
            var oXmlDom = new ActiveXObject(arr[i]);
            return oXmlDom;
        }
        catch (ex) {
            //忽略
        }
    }
    throw new Error("你的浏览器不支持XmlDocument objects");
}